package com.chat.ui.library;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chat.MyApplication;
import com.chat.R;
import com.chat.entity.DataPackage;
import com.chat.entity.File;
import com.chat.entity.ServerAction;
import com.chat.entity.event.ChannelEvent;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.chat.net.SocketClient;
import com.chat.net.socket.Channel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.netty.channel.ChannelHandlerContext;

/**
 * 文件夹
 * @author LinYang
 */
public class EditBookFragment extends Fragment {
    final int PIC_CROP = -1,WRITE_CODE = 200;
    RecyclerView recyclerView;
    ImageButton back,upload;
    TextView title;
    MyRecycleViewAdapter adapter;
    int id = 1;

    private List<HashMap<String,Object>> list=new ArrayList<HashMap<String,Object>>();
    private List<HashMap<String,Object>> mData=new ArrayList<HashMap<String,Object>>();


    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            adapter.notifyDataSetChanged();
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_editbook, container, false);
        back = view.findViewById(R.id.folder_back);
        id = getArguments().getInt("id");
        title = view.findViewById(R.id.folder_room_name);
        upload = view.findViewById(R.id.folder_upload);
        recyclerView = view.findViewById(R.id.folder_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));//垂直线性布局
        adapter=new MyRecycleViewAdapter();
        initData();
        recyclerView.setAdapter(adapter);
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });
        return view;
    }

    // 创建一个方法，用于打开相册并获取图片
    public void openGallery() {
        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .start(getContext(),this);
    }

    public void requestWritePermission(){
        // 请求写入权限
        int permission = ContextCompat.checkSelfPermission(getContext(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        // 如果应用程序没有写入权限，则请求权限
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_CODE);
        }
    }

    public void initData(){



        Map<String,Object> params = new HashMap<>();
        params.put("roomId",id);
        SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
            @Override
            public void onChannelEvent(Channel ctx, DataPackage source) {
                if(source.getCode()==200){
                    List<File> files = (List<File>) source.getDate();
                    files.stream()
                            .map(e->{
                                HashMap<String,Object> item = new HashMap<>();
                                item.put("name",e.getFileName());
                                item.put("picture",R.drawable.folder);
                                item.put("id",e.getFileId());
                                return item
;                            })
                            .forEach(e->{
                                mData.add(e);
                            });
                    Message message = Message.obtain();
                    handler.sendMessage(message);
                }
            }
        },DataPackage.request(params, ServerAction.GET_FILES_FROM_ROOM));
    }





    class  MyRecycleViewAdapter extends RecyclerView.Adapter<EditBookFragment.MyRecycleViewAdapter.ViewHolder>
    {


        public  class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView head;
            public TextView name;
            public ImageButton download;

            public ViewHolder(View convertView) {
                super(convertView);
                head = (ImageView) convertView.findViewById(R.id.folder_head);
                name = (TextView)convertView.findViewById(R.id.folder_name);
                download = (ImageButton) convertView.findViewById(R.id.folder_download);

            }
        }

        @NonNull
        @Override
        public EditBookFragment.MyRecycleViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v= LayoutInflater.from(getActivity()).inflate(R.layout.item_folder,parent, false);
            return new EditBookFragment.MyRecycleViewAdapter.ViewHolder(v);
        }



        @Override
        public void onBindViewHolder(@NonNull EditBookFragment.MyRecycleViewAdapter.ViewHolder holder, final int position) {
            //picture
            Glide.with(getActivity()).load(new MyApplication().imagebaseurl+mData.get(position).get("picture").toString()).placeholder(R.drawable.folder).into(holder.head);
            holder.name.setText("文件夹:"+String.valueOf(mData.get(position).get("name")));

            Map<String,Object> params = new HashMap<>();
            params.put("fileId",mData.get(position).get("id"));
            holder.download.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    //文件下载
                    SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
                        @Override
                        public void onChannelEvent(Channel ctx, DataPackage source) {
                            if (source.getCode() == 200) {
                                //读取二进制数组
                                byte[] fileContent = (byte[]) source.getDate();
                                // 检查是否具有写入外部存储的权限
                                if (ContextCompat.checkSelfPermission(getActivity(),
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        != PackageManager.PERMISSION_GRANTED) {

                                    // 如果没有权限，请求权限
                                    requestWritePermission();
                                } else {
                                    // 如果已经具有权限，则创建文件
                                    java.io.File directory = getActivity().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
                                    java.io.File file = new java.io.File(directory, (String) mData.get(position).get("name"));
                                    try {
                                        if(file.exists()){
                                            Log.i("com.chat","文件替换成功！"+file.getAbsoluteFile());
                                        }
                                        else if (file.createNewFile()) {
                                            Log.i("com.chat","文件写入成功！"+file.getAbsoluteFile());
                                            FileOutputStream fileOutputStream = new FileOutputStream(file);
                                            fileOutputStream.write(fileContent);
                                            fileOutputStream.flush();
                                            fileOutputStream.close();
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                        Log.e("com.chat", "文件写入失败!");
                                    }
                                }
                            }
                        }
                    },DataPackage.request(params,ServerAction.DOWNLOAD_FILE_FROM_ROOM));

                }
            });
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//<<<<<<< HEAD

//        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == PIC_CROP) {
                Uri resultUri = result.getUri();
                String picturePath = resultUri.getPath();

                try {
                    java.io.File file = new java.io.File(picturePath);
                    byte[] fileBytes = new byte[(int) file.length()];
                    FileInputStream fis = new FileInputStream(file);
                    fis.read(fileBytes);
                    fis.close();
                    Map<String,Object> params = new HashMap<>();
                    params.put("roomId",id);
                    params.put("fileName",file.getName());
                    params.put("fileContent",fileBytes);
                    SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
                        @Override
                        public void onChannelEvent(Channel ctx, DataPackage source) {
                            super.onChannelEvent(ctx, source);
                        }
                    },DataPackage.request(params,ServerAction.SEND_FILE_FROM_ROOM));

                } catch (FileNotFoundException e) {
                    Log.e("com.chat","文件读取失败！"+e.toString());
                    e.printStackTrace();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
                Log.e("com.chat",error.toString());
//=======
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == GALLAY_CODE && resultCode == Activity.RESULT_OK && data != null) {
//            // 获取选中图像的Uri
//            Uri selectedImage = data.getData();
//            String[] filePathColumn = {MediaStore.Images.Media.DATA};
//            // 通过Uri获取图像的路径
//            Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
//            cursor.moveToFirst();
//            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//            String picturePath = cursor.getString(columnIndex);
//            cursor.close();
//
//            //裁剪图片
//
//            try {
//                java.io.File file = new java.io.File(picturePath);
//                byte[] fileBytes = new byte[(int) file.length()];
//                FileInputStream fis = new FileInputStream(file);
//                fis.read(fileBytes);
//                fis.close();
//
//
//                Map<String,Object> params = new HashMap<>();
//                params.put("roomId",id);
//                params.put("fileName",file.getName());
//                params.put("fileContent",fileBytes);
//                SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
//                    @Override
//                    public void onChannelEvent(Channel ctx, DataPackage source) {
//                        super.onChannelEvent(ctx, source);
//                    }
//                },DataPackage.request(params,ServerAction.SEND_FILE_FROM_ROOM));
//
//            } catch (FileNotFoundException e) {
//                Log.e("com.chat","文件读取失败！"+e.toString());
//                e.printStackTrace();
//
//            } catch (IOException e) {
//                e.printStackTrace();
//>>>>>>> d40e431dc1f24bb84233c75a4a1d58d198a0063a
            }
        }
        else if(resultCode == WRITE_CODE){
                

        }

    }


}
